<?php


namespace App\Service\Cooperative;


use App\Constants\ErrorCode;
use App\Dao\TaskTypeDao;
use App\Exception\BusinessException;
use App\Model\TaskType;
use Hyperf\Di\Annotation\Inject;

class TaskTypeService extends BaseService
{

    /**
     * @Inject()
     * @var TaskTypeDao
     */
    protected $taskTagDao;

    public function index()
    {
        return $this->taskTagDao->where(['cooperative_id' => $this->user()->cooperative_id])->get();
    }

    /**
     * @param $id
     * @param array $data
     * @return bool
     */
    public function save($id, array $data)
    {
        if ($id) {
            /** @var TaskType $type */
            $type = $this->taskTagDao->first(['cooperative_id' => $this->user()->cooperative_id, 'id' => $id]);
            if (!$type) {
                throw new BusinessException(ErrorCode::COOPERATIVE_TYPE_NOT_FOUND);
            }
        } else {
            $type = new TaskType();
            $type->cooperative_id = $this->user()->cooperative_id;
        }
        $type->iconfont_id = $data['iconfont_id'];
        $type->tag = $data['tag'];

        return $type->save();
    }

    /**
     * @param int $id
     * @return bool|null
     * @throws \Exception
     */
    public function delete(int $id)
    {
        /** @var TaskType $type */
        $type = $this->taskTagDao->first(['cooperative_id' => $this->user()->cooperative_id, 'id' => $id]);
        if (!$type) {
            throw new BusinessException(ErrorCode::COOPERATIVE_TYPE_NOT_FOUND);
        }
        return $type->delete();
    }
}